﻿using System;
using System.Collections.Generic;

using SharedGenomics.Core;

namespace SharedGenomics.Workbench.Aspects
{
    public class LoginCachingStrategy : ICachingStrategy
    {
        private IDictionary<int, WeakReference> _cache;

        public LoginCachingStrategy()
        {
            this._cache = new Dictionary<int, WeakReference>();
        }

        public bool TryGetFromCache(int id, out object item)
        {
            item = null;
            if (this._cache.ContainsKey(id))
            {
                WeakReference weakRef = this._cache[id];
                if (weakRef.IsAlive)
                {
                    item = weakRef.Target;
                    return true;
                }
            }

            return false;
        }

        public void AddToCache(int id, object item)
        {
            item.ThrowIfNull("item");
            this._cache[id] = new WeakReference(item);
        }
    }
}
